import axios from "axios"
import type {
	AxiosInstance,
	AxiosResponse,
	InternalAxiosRequestConfig
} from "axios"
import { UniAdapter } from "uniapp-axios-adapter"
import { removeStorage, getStorage } from "./storage"
import type {responseType} from "../type"

const service : AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_URL as string,
	// baseURL: '',
	timeout: 8000,
	adapter: UniAdapter
})

// console.log(23232332,import.meta.env.VITE_APP_BASE_URL)

// interface configHeaders extends AxiosHeaderValue  {

// }

// request拦截器
service.interceptors.request.use((config : InternalAxiosRequestConfig<any>) => {
	return config
}, error => {
	Promise.reject(error)
})


// 响应拦截器
service.interceptors.response.use((res : AxiosResponse<any>) => {
	const { status } = res
	// 未设置状态码则默认成功状态
	// const code = res.data.code || 200
	// 	if (code === 401) {
	// 		return Promise.reject('（401）：请求要求身份验证。对于需要登录的网页，服务器可能返回此响应')
	// 	} else if (code === 500) {
	// 		uni.showToast({
	// 			title: msg,
	// 			duration: 2000
	// 		});

	// 		return Promise.reject(new Error(msg))
	// 	} else if (code !== 200) {
	// 		uni.showToast({
	// 			title: msg,
	// 			duration: 2000
	// 		});

	// 		return Promise.reject('error')
	// 	} else {
	// 		return res.data
	// 	}
	// uni.showLoading({
	// 	title: '加载中', 
	// 	mask: true
	// });
	// console.log(90,res)
	if (status === 401) {

	} else if (status === 200) {
		return res.data
	} else {
		uni.hideLoading()
		uni.showToast({
			icon: 'none',
			title: res.data.message || "未知错误",
			duration: 3000
		})
	}
},
	error => {
		if (error.code == "ECONMAРOРTED" || error.errMsg == 'Network Error' || error.errMsg.includes('timeout')) {
			uni.hideLoading()
			console.log("网络延迟", error)
			uni.showToast({
				icon: 'error',
				title: "网络延迟",
				duration: 3000
			})
		}
		return Promise.reject(error)
	}
)

export const getNotToken = (url : string, params : object = {}, headers : object = {}) => {
	return service<any,responseType>({
		method: 'get',
		url,
		params,
		headers: {
			...headers
		}
	})
}

export const postNotToken = (url : string, data : object = {}, headers : object = {}) => {
	return service<any,responseType>({
		method: 'post',
		url,
		data,
		headers: {
			...headers
		}
	})
}

export const get = async (url : string, params : object = {}, headers : object = {}) => {
	const token = await getStorage('token') || ''
	return service<any,responseType>({
		method: 'get',
		url,
		params,
		headers: {
			Authorization: `Bearer ${token}`,
			...headers
		}
	})
}

export const post = async (url : string, data : object = {}, headers : object = {}) => {
	const token = await getStorage('token') || ''
	return service<any,responseType>({
		method: 'post',
		url,
		data,
		headers: {
			Authorization: `Bearer ${token}`,
			...headers
		}
	})
}